#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QSerialPort>
#include <QMessageBox>
#include <QDebug>
#include <QFileDialog>

#include "dialog_about.h"
#include "dialog_comconfig.h"
#include "dialog_console_1.h"
#include "dialog_console_2.h"
#include "dialog_console_3.h"
#include "serial.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    QPalette palette0;
    QPalette palette1;
    palette0.setColor(QPalette::Background,QColor::fromRgb(245,245,245));
    palette1.setColor(QPalette::Background,QColor::fromRgb(245,245,245));

    ui->tabWidget->setAutoFillBackground(true);
    ui->tabWidget->setPalette(palette0);

    ui->tabWidget->widget(0)->setAutoFillBackground(true);
    ui->tabWidget->widget(0)->setPalette(palette1);

    ui->tabWidget->widget(1)->setAutoFillBackground(true);
    ui->tabWidget->widget(1)->setPalette(palette1);

    ui->tabWidget->widget(2)->setAutoFillBackground(true);
    ui->tabWidget->widget(2)->setPalette(palette1);

    ui->tabWidget->widget(3)->setAutoFillBackground(true);
    ui->tabWidget->widget(3)->setPalette(palette1);

    ui->tabWidget->widget(4)->setAutoFillBackground(true);
    ui->tabWidget->widget(4)->setPalette(palette1);

    this->setPalette(palette0);

    setWindowTitle("串口下载工具 V1.0.2");

    //QPalette palette(this->palette());
   // palette.setColor(QPalette::Background, Qt:: black);
    //this->setPalette(palette);

    serial_rec_len  = 0;
    serial_send_len = 0;

    p_Com = NULL;
    p_Com = new Dialog_ComConfig();

    p_About = NULL;
    p_About = new Dialog_About();

    p_Con1 = NULL;
    p_Con1 = new Dialog_Console_1();

    p_Con2 = NULL;
    p_Con2 = new Dialog_Console_2();

    p_Con3 = NULL;
    p_Con3 = new Dialog_Console_3();

    ui->connect->setEnabled(false);
    ui->disconnect->setEnabled(false);

    connect(p_Com, &Dialog_ComConfig::signal_com_connect, this,&MainWindow::slot_connect);
    connect(p_Com, &Dialog_ComConfig::signal_com_disconnect,this,&MainWindow::slot_disconnect);
    connect(p_Com->mySerial->serial,SIGNAL(readyRead()),this,SLOT(slot_Read_Data()));

    connect(p_Con1,&Dialog_Console_1::signal_con1_edit,this,&MainWindow::slot_con1_enter);
    connect(p_Con2,&Dialog_Console_2::signal_con1_edit,this,&MainWindow::slot_con2_enter);
    connect(p_Con3,&Dialog_Console_3::signal_con1_edit,this,&MainWindow::slot_con3_enter);

    ui->pushButton_Con_Edit_1->setEnabled(ui->checkBox_2->isChecked());
    ui->pushButton_Con_Edit_2->setEnabled(ui->checkBox_3->isChecked());
    ui->pushButton_Con_Edit_3->setEnabled(ui->checkBox_4->isChecked());

    ui->pushButton_Con_Edit_1->setText(tr("选中发送、点击编辑"));
    ui->pushButton_Con_Edit_2->setText(tr("选中发送、点击编辑"));
    ui->pushButton_Con_Edit_3->setText(tr("选中发送、点击编辑"));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_config_triggered()
{
    if(p_Com != NULL)
    {
        p_Com->exec();
    }
}

void MainWindow::on_about_triggered()
{
    if(p_About != NULL)
    {
        p_About->exec();
    }
}

void MainWindow::on_quit_triggered()
{
    this->close();
}

void MainWindow::slot_connect()
{
    QString com_name;
    com_name = p_Com->mySerial->Get_Serial_Com();
    ui->label_ComStatus->setText("串口 "+com_name+" 已开启");
    ui->connect->setEnabled(false);
    ui->disconnect->setEnabled(true);
}

void MainWindow::slot_disconnect()
{
    ui->label_ComStatus->setText("串口已关闭");
    ui->connect->setEnabled(true);
    ui->disconnect->setEnabled(false);
}



void MainWindow::on_disconnect_triggered()
{
    p_Com->mySerial->Close_Serial();
    p_Com->Get_Com_comboBoxCom_Ptr()->setEnabled(true);
    p_Com->Get_Com_comboBoxBaud_Ptr()->setEnabled(true);
    p_Com->Get_Com_comboBoxData_Ptr()->setEnabled(true);
    p_Com->Get_Com_comboBoxStop_Ptr()->setEnabled(true);
    p_Com->Get_Com_comboBoxCheck_Ptr()->setEnabled(true);
    p_Com->Get_Com_Connect()->setEnabled(true);
    p_Com->Set_Com_Flush_PushButton(false);

    ui->label_ComStatus->setText("串口已关闭");
    ui->connect->setEnabled(true);
    ui->disconnect->setEnabled(false);
}

void MainWindow::on_connect_triggered() //mainwindow界面连接
{
    QString com_name;
    com_name = p_Com->mySerial->Get_Serial_Com();

    p_Com->mySerial->Open_Serial();

    if(p_Com->mySerial->Get_Serial_Connect() == true)
    {
        p_Com->Get_Com_comboBoxCom_Ptr()->setEnabled(false);
        p_Com->Get_Com_comboBoxBaud_Ptr()->setEnabled(false);
        p_Com->Get_Com_comboBoxData_Ptr()->setEnabled(false);
        p_Com->Get_Com_comboBoxStop_Ptr()->setEnabled(false);
        p_Com->Get_Com_comboBoxCheck_Ptr()->setEnabled(false);
        p_Com->Get_Com_Connect()->setEnabled(false);
        p_Com->Set_Com_Flush_PushButton(true);

        ui->label_ComStatus->setText("串口 "+com_name+" 已开启");
        ui->connect->setEnabled(false);
        ui->disconnect->setEnabled(true);
    }
}

void MainWindow::slot_Read_Data()
{
    QByteArray rec_data;
    int rec_len;
    int rec_arr[100];
    char rec_arr2[1024];
    static bool flag = false;

    int data;
    int i=0;
    rec_len = (p_Com->mySerial->serial->bytesAvailable());

    serial_rec_len  = serial_rec_len + rec_len;

    if(ui->comboBox_disp->currentText() == tr("Char显示"))
    {
        if(flag == false)
        {
            flag = true;
            qDebug()<<"flag = "<<flag<<endl;
            serial_rec_data.clear();
            ui->textBrowser_RecData->clear();

        }
        rec_data = p_Com->mySerial->serial->readAll();
        rec_data = rec_data.insert(0,"\r收-->");
        serial_rec_data = serial_rec_data + rec_data;
        ui->textBrowser_RecData->setText(serial_rec_data);
    }
    else if(ui->comboBox_disp->currentText() == tr("Hex显示"))
    {
        if(flag == true)
        {
            flag = false;
            qDebug()<<"flag = "<<flag<<endl;
            serial_rec_data.clear();
            ui->textBrowser_RecData->clear();
        }
        rec_data = p_Com->mySerial->serial->readAll();

        rec_data = rec_data.toHex().toUpper();

        for(i=1;i<rec_len;i++)
        {
            rec_data.insert(2*i+i-1," ");
        }
        rec_data = rec_data.insert(0,"\r收-->");

        serial_rec_data = serial_rec_data + rec_data;

        ui->textBrowser_RecData->setText(serial_rec_data);

    }
    ui->textBrowser_RecData->moveCursor(QTextCursor::End);
    ui->label_RX_Cnt->setText(QString::number(serial_rec_len));
}

void MainWindow::on_pushButton_ClearCnt_clicked()
{
    serial_rec_len = 0;
    serial_send_len = 0;

    ui->label_RX_Cnt->setText(QString::number(serial_rec_len));
    ui->label_TX_Cnt->setText(QString::number(serial_send_len));
}

void MainWindow::on_pushButton_ClearRxWin_clicked()
{
    serial_rec_data.clear();
    ui->textBrowser_RecData->clear();
}

QByteArray MainWindow::HexStringToByteArray(QString HexString)
{
    bool ok;
    QByteArray ret;

    HexString = HexString.trimmed();
    HexString = HexString.simplified();
    QStringList sl = HexString.split(" ");

    foreach (QString s, sl) {
        if(!s.isEmpty())
        {
            char c = s.toInt(&ok,16)&0xFF;
            if(ok){
                ret.append(c);
            }else{
                qDebug()<<"非法的16进制字符："<<s;
                QMessageBox::warning(0,tr("错误："),QString("非法的16进制字符: \"%1\"").arg(s));
            }
        }
    }
    qDebug()<<ret;
    return ret;
}

void MainWindow::on_pushButton_Send_clicked()
{
    bool ok;
    QString send_buff;
    QByteArray f;
    int send_length;
    QByteArray rec_data;
    int i;


    if(p_Com->mySerial->serial->isOpen() == false)
    {
        QMessageBox::warning(NULL,"抱歉","串口未开启！"/*,QMessageBox::Yes*/);
        return;
    }
    send_buff = ui->textEdit_SendData->toPlainText();

    send_length = (p_Com->mySerial->serial->bytesToWrite());

    if(ui->comboBox_2->currentText() == tr("Char发送"))
    {
        f = send_buff.toLatin1();

        f = f.insert(0,"\r发-->");
        serial_rec_data = serial_rec_data + f;
        ui->textBrowser_RecData->setText(serial_rec_data);

    }
    else if(ui->comboBox_2->currentText() == tr("Hex发送"))
    {
        String_Convert_To_Hex(send_buff,f);

        rec_data = f.toHex().toUpper();

        for(i=1;i<send_length;i++)
        {
            rec_data.insert(2*i+i-1,"  ");
        }
        rec_data = rec_data.insert(0,"\r发-->");

        serial_rec_data = serial_rec_data + rec_data;

        ui->textBrowser_RecData->setText(serial_rec_data);
    }

    char *temp = f.data();

    p_Com->mySerial->serial->write(temp);
//    f = f.insert(0,"\r发-->");
//    serial_rec_data = serial_rec_data + f;
//    ui->textBrowser_RecData->setText(serial_rec_data);
    ui->textBrowser_RecData->moveCursor(QTextCursor::End);
    serial_send_len = serial_send_len + send_length;
    ui->label_TX_Cnt->setText(QString::number(serial_send_len));
}

void MainWindow::on_pushButton_ClearTxWin_clicked()
{
    ui->textEdit_SendData->clear();
}

void MainWindow::String_Convert_To_Hex(QString str, QByteArray &arr)
{
    int hexdata,lowhexdata;
    int hexdatalen = 0;
    int len = str.length();
    arr.resize(len/2);
    char lstr,hstr;
    for(int i=0; i<len; )
    {
        //char lstr,
//        hstr=str[i].toAscii();
        hstr = str[i].toLatin1();
        if(hstr == ' ')
        {
            i++;
            continue;
        }
        i++;
        if(i >= len)
            break;
//        lstr = str[i].toAscii();
        lstr = str[i].toLatin1();
        hexdata = ConvertHexChar(hstr);
        lowhexdata = ConvertHexChar(lstr);
        if((hexdata == 16) || (lowhexdata == 16))
            break;
        else
            hexdata = hexdata*16+lowhexdata;
        i++;
        arr[hexdatalen] = (char)hexdata;
        hexdatalen++;
    }
    arr.resize(hexdatalen);
}

char MainWindow::ConvertHexChar(char ch)
{
    if((ch >= '0') && (ch <= '9'))
            return ch-0x30;
        else if((ch >= 'A') && (ch <= 'F'))
            return ch-'A'+10;
        else if((ch >= 'a') && (ch <= 'f'))
            return ch-'a'+10;
        else return (-1);
}

void MainWindow::on_pushButton_Con_Edit_1_clicked()
{
    if(p_Con1 != NULL)
    {
        p_Con1->exec();
    }
}

void MainWindow::on_pushButton_Con_Edit_2_clicked()
{
    if(p_Con2 != NULL)
    {
        p_Con2->exec();
    }
}

void MainWindow::on_pushButton_Con_Edit_3_clicked()
{
    if(p_Con3 != NULL)
    {
        p_Con3->exec();
    }
}

void MainWindow::on_checkBox_2_stateChanged(int arg1)
{
    if(ui->checkBox_2->isChecked() == false)
    {
        ui->pushButton_Con_Edit_1->setEnabled(false);
    }
    else if(ui->checkBox_2->isChecked() == true)
    {
        ui->pushButton_Con_Edit_1->setEnabled(true);
        ui->pushButton_Con_Edit_2->setEnabled(false);
        ui->pushButton_Con_Edit_3->setEnabled(false);
        ui->checkBox_3->setChecked(false);
        ui->checkBox_4->setChecked(false);


    }
}

void MainWindow::on_checkBox_3_stateChanged(int arg1)
{
    if(ui->checkBox_3->isChecked() == false)
    {
        ui->pushButton_Con_Edit_2->setEnabled(false);
    }
    else if(ui->checkBox_3->isChecked() == true)
    {
        ui->pushButton_Con_Edit_1->setEnabled(false);
        ui->pushButton_Con_Edit_2->setEnabled(true);
        ui->pushButton_Con_Edit_3->setEnabled(false);
        ui->checkBox_2->setChecked(false);
        ui->checkBox_4->setChecked(false);
    }
}

void MainWindow::on_checkBox_4_stateChanged(int arg1)
{
    if(ui->checkBox_4->isChecked() == false)
    {
        ui->pushButton_Con_Edit_3->setEnabled(false);
    }
    else if(ui->checkBox_4->isChecked() == true)
    {
        ui->pushButton_Con_Edit_1->setEnabled(false);
        ui->pushButton_Con_Edit_2->setEnabled(false);
        ui->pushButton_Con_Edit_3->setEnabled(true);
        ui->checkBox_2->setChecked(false);
        ui->checkBox_3->setChecked(false);
    }
}

void MainWindow::slot_con1_enter()
{
    qDebug()<<"rec slot"<<endl;
    if(ui->checkBox_2->isChecked() == true)
    {
        ui->pushButton_Con_Edit_1->setText(p_Con1->Get_Label_Name());

        p_Con1->close();
        qDebug()<<"close1"<<endl;
    }

    if(ui->checkBox_3->isChecked() == true)
    {
        ui->pushButton_Con_Edit_1->setText(p_Con2->Get_Label_Name());

        p_Con2->close();
        qDebug()<<"close2"<<endl;
    }

    if(ui->checkBox_3->isChecked() == true)
    {
        ui->pushButton_Con_Edit_1->setText(p_Con3->Get_Label_Name());

        p_Con3->close();
        qDebug()<<"close3"<<endl;
    }

}

void MainWindow::slot_con2_enter()
{
      ui->pushButton_Con_Edit_2->setText(p_Con2->Get_Label_Name());

}

void MainWindow::slot_con3_enter()
{
    qDebug()<<"click"<<endl;
    ui->pushButton_Con_Edit_3->setText(p_Con3->Get_Label_Name());

}

void MainWindow::on_pushButton_Send1_clicked()
{
    bool ok;
    QString send_buff;
    QByteArray f;
    int send_length;
    QByteArray rec_data;
    int i;

    if(p_Com->mySerial->serial->isOpen()==false)
    {
        QMessageBox::warning(NULL,"抱歉","串口未打开！"/*,QMessageBox::Yes*/);

        return;
    }

    send_length = p_Com->mySerial->serial->bytesToWrite();

    if(ui->checkBox_2->isChecked() == true)
    {
        send_buff = p_Con1->Get_Con1_Edit_Prt()->toPlainText();

        if(p_Con1->Get_ComboBox_Prt()->currentText() == tr("Char发送"))
        {
            f = send_buff.toLatin1();

            f = f.insert(0,"\r发-->");
            serial_rec_data = serial_rec_data + f;
            ui->textBrowser_RecData->setText(serial_rec_data);
        }
        else if(p_Con1->Get_ComboBox_Prt()->currentText() == tr("Hex发送"))
        {
            String_Convert_To_Hex(send_buff,f);

            rec_data = f.toHex().toUpper();

            for(i=1;i<send_length;i++)
            {
                rec_data.insert(2*i+i-1,"  ");
            }
            rec_data = rec_data.insert(0,"\r发-->");

            serial_rec_data = serial_rec_data + rec_data;

            ui->textBrowser_RecData->setText(serial_rec_data);
        }
    }
    else if(ui->checkBox_3->isChecked() == true)
    {
        send_buff = p_Con2->Get_Con2_Edit_Prt()->toPlainText();

        if(p_Con2->Get_ComboBox_Prt()->currentText() == tr("Char发送"))
        {
            f = send_buff.toLatin1();

            f = f.insert(0,"\r发-->");
            serial_rec_data = serial_rec_data + f;
            ui->textBrowser_RecData->setText(serial_rec_data);
        }
        else if(p_Con2->Get_ComboBox_Prt()->currentText() == tr("Hex发送"))
        {
            String_Convert_To_Hex(send_buff,f);

            rec_data = f.toHex().toUpper();

            for(i=1;i<send_length;i++)
            {
                rec_data.insert(2*i+i-1,"  ");
            }
            rec_data = rec_data.insert(0,"\r发-->");

            serial_rec_data = serial_rec_data + rec_data;

            ui->textBrowser_RecData->setText(serial_rec_data);
        }
    }
    else if(ui->checkBox_4->isChecked() == true)
    {
        send_buff = p_Con3->Get_Con3_Edit_Prt()->toPlainText();

        if(p_Con3->Get_ComboBox_Prt()->currentText() == tr("Char发送"))
        {
            f = send_buff.toLatin1();

            f = f.insert(0,"\r发-->");
            serial_rec_data = serial_rec_data + f;
            ui->textBrowser_RecData->setText(serial_rec_data);
        }
        else if(p_Con3->Get_ComboBox_Prt()->currentText() == tr("Hex发送"))
        {
            String_Convert_To_Hex(send_buff,f);

            rec_data = f.toHex().toUpper();

            for(i=1;i<send_length;i++)
            {
                rec_data.insert(2*i+i-1,"  ");
            }
            rec_data = rec_data.insert(0,"\r发-->");

            serial_rec_data = serial_rec_data + rec_data;

            ui->textBrowser_RecData->setText(serial_rec_data);
        }
    }

    char *temp = f.data();

    p_Com->mySerial->serial->write(temp);
    ui->textBrowser_RecData->moveCursor(QTextCursor::End);
    serial_send_len = serial_send_len + send_length;
    ui->label_TX_Cnt->setText(QString::number(serial_send_len));
}

void MainWindow::on_pushButton_OpenFile_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("打开曲线数据表格"),"./",tr("打开一条曲线(*.csv *.xlsx)"));

    ui->textBrowser_FileName->setText(fileName);
}

